// pages/statistics/index.js
Page({
  data: {
    statistics: {
      total: 0,
      completed: 0,
      rate: 0
    },
    filters: {
      month: '',
      responsible: ''
    },
    months: Array.from({length: 12}, (_, i) => i + 1),
    responsibleList: [],
    chartData: {}
  },

  onLoad: function() {
    this.loadResponsibleList();
  },

  onShow: function() {
    this.loadStatistics();
    this.prepareChartData();
  },

  // 加载统计数据
  loadStatistics: function() {
    const app = getApp();
    const statistics = app.getStatistics(this.data.filters);
    this.setData({ statistics });
  },

  // 加载负责人列表
  loadResponsibleList: function() {
    const app = getApp();
    const todos = app.globalData.todos;
    const responsibleSet = new Set();
    
    todos.forEach(todo => {
      if (todo.responsible) {
        responsibleSet.add(todo.responsible);
      }
    });
    
    this.setData({
      responsibleList: Array.from(responsibleSet)
    });
  },

  // 设置月份筛选
  setMonth: function(e) {
    const month = this.data.months[e.detail.value];
    this.setData({
      'filters.month': month
    });
    this.loadStatistics();
    this.prepareChartData();
  },

  // 设置负责人筛选
  setResponsible: function(e) {
    const responsible = e.detail.value;
    this.setData({
      'filters.responsible': responsible
    });
    this.loadStatistics();
    this.prepareChartData();
  },

  // 清除筛选
  clearFilters: function() {
    this.setData({
      filters: {
        month: '',
        responsible: ''
      }
    });
    this.loadStatistics();
    this.prepareChartData();
  },

  // 准备图表数据
  prepareChartData: function() {
    const app = getApp();
    const todos = app.getTodos(this.data.filters);
    
    // 按月份统计
    const monthlyData = {};
    todos.forEach(todo => {
      const date = new Date(todo.planEndTime);
      const month = date.getMonth() + 1;
      if (!monthlyData[month]) {
        monthlyData[month] = {
          total: 0,
          completed: 0
        };
      }
      monthlyData[month].total++;
      if (todo.status === 'completed') {
        monthlyData[month].completed++;
      }
    });
    
    // 按负责人统计
    const responsibleData = {};
    todos.forEach(todo => {
      if (!todo.responsible) return;
      
      if (!responsibleData[todo.responsible]) {
        responsibleData[todo.responsible] = {
          total: 0,
          completed: 0
        };
      }
      responsibleData[todo.responsible].total++;
      if (todo.status === 'completed') {
        responsibleData[todo.responsible].completed++;
      }
    });
    
    this.setData({
      chartData: {
        monthly: monthlyData,
        responsible: responsibleData
      }
    });
  }
}));